import axios, { InternalAxiosRequestConfig } from 'axios'
import { ElLoading } from 'element-plus'
import QS from "qs"

const request = axios.create({
    timeout:5000
})
let loading:any = null
request.interceptors.request.use((config:InternalAxiosRequestConfig)=>{
    config.headers = config.headers || {}
    config.headers['token'] = ""
    loading = ElLoading.service({
        fullscreen: true,
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      return config 
},error => Promise.reject(error))

request.interceptors.response.use(
    res =>{
        if(loading){
            loading.close()
        }
        if(res && res.data){
            return res.data
        }else{
            return Promise.reject("请求错误")
        }
    },
    error=>{
        if(loading){
            loading.close()
        } 
        return Promise.reject(error.message || "")
    }
)

export const get = (url:string, params?:object, responseType?:ResponseType) => {
    return new Promise((resolve, reject) => {
        request
            .get(url, {
                params,
                responseType,
            })
            .then(res => resolve(res))
            .catch(err => reject(err));
    });
};

export const post = async (url:string, params = {}) => {
    return new Promise((resolve, reject) => {
        request
            .post(url, params)
            .then(res => resolve(res))
            .catch(err => reject(err));
    });
};
export const postForm = (url:string, params:object) => {
    return new Promise((resolve, reject) => {
        request
            .post(url, params, {
                headers: { "Content-Type": "application/x-www-form-urlencoded;charset=utf-8" },
                transformRequest: [(data) => {
                    return QS.stringify(data);
                }]
            })
            .then(res => {
                resolve(res);
            })
            .catch(err => {
                reject(err);
            });
    });
};